package com.pagepub.expo.action.corp;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.pagepub.core.ftp.UploadImage;
import com.pagepub.core.ftp.UploadXml;
import com.pagepub.core.tag.message.HtmlMessageBox;
import com.pagepub.core.utils.Config;
import com.pagepub.core.utils.ExtendString;
import com.pagepub.core.utils.MyUtil;
import com.pagepub.core.utils.StringUtil;
import com.pagepub.expo.action.BaseAction;
import com.pagepub.expo.entity.AppDict;
import com.pagepub.expo.entity.CorpCatalog;
import com.pagepub.expo.entity.CorpCommpany;
import com.pagepub.expo.entity.CorpPublication;
import com.pagepub.expo.entity.CorpPublicationPage;
import com.pagepub.expo.manager.AppDictMng;
import com.pagepub.expo.manager.AppSeqMng;
import com.pagepub.expo.manager.CorpCatalogMng;
import com.pagepub.expo.manager.CorpPublicationMng;
import com.pagepub.expo.manager.CorpPublicationPageMng;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class CorpPublicationAction extends BaseAction implements
		ModelDriven<CorpPublication>, Preparable {
	private static final long serialVersionUID = 1L;

	@Autowired
	@Qualifier("corpPublicationMng")
	private CorpPublicationMng corpPublicationMng;

	@Autowired
	@Qualifier("corpPublicationPageMng")
	private CorpPublicationPageMng corpPublicationPageMng;
	
	@Autowired
	@Qualifier("corpCatalogMng")
	private CorpCatalogMng corpCatalogMng;

	@Autowired
	@Qualifier("appDictMng")
	private AppDictMng appDictMng;

	@Autowired
	@Qualifier("appSeqMng")
	private AppSeqMng appSeqMng;

	private CorpPublication corpPublication;

	private File thumb;
	
	private File endpicture;


	private String thumbFileName; // 上传的文件名 (1.系统自动注入 2.变量命名有规则:
									// 前台对象名+"FileName")
	private String endpictureFileName; // 上传的文件名 (1.系统自动注入 2.变量命名有规则:
	// 前台对象名+"FileName")

	public CorpPublication getModel() {
		return corpPublication;
	}

	public void prepare() throws Exception {
		this.clearErrorsAndMessages();

		String actionName = ServletActionContext.getActionMapping().getName();
		if ("corpPublication_show".equals(actionName)
				|| "corpPublication_modify".equals(actionName)) {
			HttpServletRequest request = ServletActionContext.getRequest();
			if ("corpPublication_show".equals(actionName)) {
				String dictCode = "1002";
				String parentId = "0";
				corpPublication = new CorpPublication();
				List<AppDict> typeDicts = appDictMng
						.getfindByDictCode(dictCode);
				request.setAttribute("typeDicts", typeDicts);
				List<CorpCatalog> corpCatalogs = corpCatalogMng
						.getCorpCatalogByParentId(parentId);
				request.setAttribute("corpCatalogs", corpCatalogs);
				request.setAttribute("typeDicts", typeDicts);
			} else {
				String id = request.getParameter("id");
				corpPublication = corpPublicationMng.findById(StringUtil.stringToInt(id));
			}
		}

	}

	
	
	public String show() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return "newshow";
	}

	
	public String editui() {
		String dictCode = "1002";
		String parentId = "0";
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		CorpCommpany corpCommpany = (CorpCommpany) session.getAttribute("corpCommpany");
		String corpId = corpCommpany.getId()+"";

		int corpTypeId = corpCommpany.getCorpTypeId();
		String publicationid = ExtendString.nullToSpaceNoTrim(request
				.getParameter("publicationid"));
		corpPublication = corpPublicationMng.findById(StringUtil.stringToInt(publicationid));

		List<AppDict> typeDicts = appDictMng
		.getfindByDictCode(dictCode);
		request.setAttribute("typeDicts", typeDicts);
		List<CorpCatalog> corpCatalogs = corpCatalogMng
				.getCorpCatalogByParentId(parentId);
		request.setAttribute("corpCatalogs", corpCatalogs);
		request.setAttribute("typeDicts", typeDicts);
		request.setAttribute("corpPublication", corpPublication);
		request.setAttribute("imagepath", Config.ImageServerURL_CORPPUBIMG);
		System.out.println(Config.BOOKURL);
		request.setAttribute("bookurl", Config.BOOKURL);
		return "editui";
	}
	public String editpubui() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String publicationId=request.getParameter("publicationid");
		request.setAttribute("publicationid",publicationId);
		return "editpub";
	}
	public String delete() {
		String display = "list";
		HttpServletRequest request = ServletActionContext.getRequest();
		// 获取keyword
		String publicationid = ExtendString.nullToSpaceNoTrim(request
				.getParameter("publicationid"));
		HttpSession session = request.getSession(true);
		CorpCommpany corpCommpany = (CorpCommpany) session.getAttribute("corpCommpany");
		String corpId = corpCommpany.getId()+"";
		// 以下为高级设置为空时调用默认设置
		HtmlMessageBox hmb = new HtmlMessageBox();
		hmb.setEnabledTimer(true);// 是否在页面有计时
		hmb.setTimer(5);// 倒计时秒数,默认5秒
		hmb.setMessageOnPageType(HtmlMessageBox.MESSAGE_ON_PAGE_SPECIFY_URL);// .MESSAGE_ON_PAGE_PREACTION_URL);
		hmb.setMessageOnPageURL("javascript:parent.closelayer(true)");

		
		if (corpPublicationMng.isDeletePublication(corpId,
				StringUtil.stringToInt(publicationid))) {
	
			hmb.setMessage("删除成功！");// 提示信息
			hmb
					.setForwardUrl(new String[] { "javascript:parent.closelayer(true);" });// 提示信息页面设置链接到指定位置


			hmb.setLinkMsg(new String[] { "到列表" });// 链接到指定位置的提示信息
		}
		display = this.displayMessage(request,hmb, "big");
		return display;
	}
	
	
	public String editpub() {
		// 获取keyword
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String publicationId=request.getParameter("publicationid");
		if(publicationId!=null&&!"".equalsIgnoreCase(publicationId)){
			publicationId=publicationId.trim();
			CorpPublication publication=corpPublicationMng.findById(StringUtil.stringToInt(publicationId));
			List publicationPagesList= corpPublicationPageMng.findByPubId(StringUtil.stringToInt(publicationId.trim()));
			if(publicationPagesList!=null&&publicationPagesList.size()>0){
				StringBuffer pubXml=new StringBuffer();
				long width=0;
				long height= publication.getHeight() * 45 / 100;
				if (publication.getPubType() == 1) {				
					width=(publication.getWidth() * 45 / 100);							
				} else {
					width=(publication.getWidth() * 45 / 100) * 2;		
				}
				
				pubXml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
				pubXml.append("<qz version=\"1.0\">");
				pubXml.append("<pubid>"+publication.getId()+"</pubid>");
				pubXml.append("<path>"+ Config.ImageServerURL_CORPPUBIMG+publication.getPubPath()+"/</path>");				
				pubXml.append("<width>"+width+ "</width>");
				pubXml.append("<height>"+height+"</height>");
				pubXml.append("<thumb>thumb/small_"+publication.getThumbPath()+"</thumb>");
				pubXml.append("<end>thumb/small_"+publication.getEndPath()+"</end>");				
				pubXml.append("<body>");
				String thumb="";
				for(Iterator ir=publicationPagesList.iterator();ir.hasNext();){
					CorpPublicationPage pubPage=(CorpPublicationPage) ir.next();
					if(pubPage!=null){
						if(pubPage.getThumbPath().indexOf("swf")>-1){
							thumb="ipages/"+pubPage.getIpagePath();
						}else{
							thumb="thumb/"+pubPage.getThumbPath();
						}						
						pubXml.append("<page>");
						pubXml.append("<pageid>"+pubPage.getId()+"</pageid>");
						pubXml.append("<thumb>"+thumb+"</thumb>");
						pubXml.append("<url>ipages/"+pubPage.getIpagePath()+"</url>");
						pubXml.append("<order>"+pubPage.getOrderby()+"</order>");
						pubXml.append("</page>");
					}
				}
			pubXml.append("</body>");
			  pubXml.append("</qz>");
			  try {
				response.getWriter().print(pubXml.toString());
			} catch (IOException e) {
				// TODO 自动生成 catch 块

				e.printStackTrace();
			}				
			}
		}
		
		return null;
	}
	
	public String deletepub(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		CorpPublication publication = new CorpPublication();
		String temppubid = "", publicationpageid = "", publicationid = "", orderby = "";
		String[] tempstr = null;
		// 获取keyword
		String[] pubid = request.getParameterValues("pubid");
        List publicationPageIdList=new ArrayList();
		if (pubid != null && pubid.length > 0) {
			for (int i = 0; i < pubid.length; i++) {
				temppubid = pubid[i];
				tempstr = temppubid.split("/");
				publicationpageid = ExtendString.nullToSpaceNoTrim(tempstr[0]);				
				publicationid = ExtendString.nullToSpaceNoTrim(tempstr[1]);				
				publicationPageIdList.add(publicationpageid);
			}
			corpPublicationPageMng.isDeletePublicationpage(publicationPageIdList);
		}
		try {
			response.getWriter().print("ok");
		} catch (IOException e1) {
			// TODO 自动生成 catch 块

			e1.printStackTrace();
		}		
		String loginIp = request.getRemoteAddr();
		Date sysDate = new Date();
		
		try {			

			if (publicationid != null && !"".equalsIgnoreCase(publicationid)) {
				List publist = corpPublicationPageMng.findByPubId(StringUtil.stringToInt(publicationid));
				publication = corpPublicationMng.findById(StringUtil.stringToInt(publicationid));
				String root = ServletActionContext.getServletContext().getRealPath(
				"/expo/pub");
				// 生产XML
				new UploadXml().UploadXml(publication, publist, root);
			} 
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;

	}
	
	public String editpubcontent(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		CorpPublication publication;
		List publicationPageList = new ArrayList();
		String[] tempstr = null;
		String[] pubid=null;
		String temppubid = "", publicationpageid = "", publicationid = "", orderby = "";
		// 获取参数
		String param=request.getParameter("pubid");
		if(param!=null&&!"".equalsIgnoreCase(param)){
			param=param.trim();
			pubid = param.split(";");
		}	

		if (pubid != null && pubid.length > 0) {
			for (int i = 0; i < pubid.length; i++) {
				temppubid = pubid[i];
				tempstr = temppubid.split("/");
				publicationpageid = ExtendString.nullToSpaceNoTrim(tempstr[0]);	
				orderby=ExtendString.nullToSpaceNoTrim(tempstr[1]);
				publicationid = ExtendString.nullToSpaceNoTrim(tempstr[2]);
				CorpPublicationPage publicationpage=corpPublicationPageMng.findById(StringUtil.stringToLong(publicationpageid));
				publicationpage.setOrderby(StringUtil.stringToInt(orderby));
				if(publicationpage!=null)					
					publicationPageList.add(publicationpage);

			}
		}
	
		if (corpPublicationPageMng.updatePubOrder(publicationPageList)) {
			List publist = corpPublicationPageMng.findByPubId(StringUtil.stringToInt(publicationid));
			publication = corpPublicationMng.findById(StringUtil.stringToInt(publicationid));
			String root = ServletActionContext.getServletContext().getRealPath(
			"/expo/pub");
			// 生产XML
			new UploadXml().UploadXml(publication, publist, root);
			
		}		
        try {
			response.getWriter().print("ok");
		} catch (IOException e) {
			// TODO 自动生成 catch 块

			e.printStackTrace();
		}
		return null;

	}
	
	public String list() {
		int pageSize=10;
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		CorpCommpany corpCommpany = (CorpCommpany) session.getAttribute("corpCommpany");
		String corpId = corpCommpany.getId()+"";
		

		HashMap<String,Object> param =new HashMap<String,Object>();
//    	按关键字查询
		String key=request.getParameter("key");			
		if(key!=null&& key.length()>0){
			param.put("title", key);
			request.setAttribute("key",key);
		}
			
		if(corpId!=null&& corpId.length()>0){
			param.put("corpId", corpId);
		}
		param.put("isAuditing",new Integer(1));
		param.put("isValid",new Integer(1));
		int currentPage=1; 
		String currentpageTemp=request.getParameter("currentpage");
		if(currentpageTemp!=null){
			try {
				currentPage=new Integer(currentpageTemp).intValue();	
			} catch (Exception e) {
				currentPage=1;
			}
			
		}
		
    	int pubcount = corpPublicationMng.getCount(param);
    	request.setAttribute("pubcount", pubcount);
		request.setAttribute("currentpage",new Integer(currentPage));  	
		request.setAttribute("pageStytle", "bbstext");
    	String searchStr=MyUtil.getParams(request);
		request.setAttribute("searchStr",searchStr);
		List<CorpPublication> corpPublicationList = corpPublicationMng.findByPage(currentPage, pageSize, param); 
		request.setAttribute("corpPublicationList", corpPublicationList); 
		
		
		String dictCode = "1002";
		String parentId = "0";
		
		request.setAttribute("typeDicts", appDictMng
				.getfindByDictCode(dictCode));
		request.setAttribute("corpCatalogs", corpCatalogMng
				.getCorpCatalogByParentId(parentId));
		request.setAttribute("imagepath", Config.ImageServerURL_CORPPUBIMG);
		request.setAttribute("thumbpath", Config.FileNameTopThumb);
		String controlCode="空间大小";
//		查找限制数目;
		List dictList=(List) session.getAttribute("dict");
		long leftSize=0;
		if(dictList!=null&&dictList.size()>0){
			for(Iterator ir=dictList.iterator();ir.hasNext();){
				AppDict dict=(AppDict) ir.next();
				if(dict!=null){
					if(dict.getClassCode().indexOf(controlCode)>-1){
						//int count=	corpPublicationMng.getCount(param);
						long restrainSize=StringUtil.stringToLong(dict.getClassValue())*1024*1024;
					    leftSize=((restrainSize-pubcount)/1024)/1024;
					    if(leftSize<0) leftSize=0;
						break;
					}
				}
			}
			
		}
		request.setAttribute("leftsize", leftSize);
//		电子书剩余空间
		request.setAttribute("leftsize", leftSize);
		String fileFormat="*.jpg;*.JPG;*.jpeg;*,JPEG;*swf";
		request.setAttribute("fileformat",fileFormat);
		return "success";
	}
	

	public String listnoauditing() {
		int pageSize=10;
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		CorpCommpany corpCommpany = (CorpCommpany) session.getAttribute("corpCommpany");
		String corpId = corpCommpany.getId()+"";
		
		HashMap<String,Object> param =new HashMap<String,Object>();
//    	按关键字查询
		String key=request.getParameter("key");			
		if(key!=null&& key.length()>0){
			param.put("title", key);
			request.setAttribute("key",key);
		}
			
		if(corpId!=null&& corpId.length()>0){
			param.put("corpId", corpId);
		}
		
		param.put("isAuditing",new Integer(0));
		
		int currentPage=1; 
		String currentpageTemp=request.getParameter("currentpage");
		if(currentpageTemp!=null){
			try {
				currentPage=new Integer(currentpageTemp).intValue();	
			} catch (Exception e) {
				currentPage=1;
			}
			
		}
    	int pubcount = corpPublicationMng.getCount(param);
    	request.setAttribute("pubcount", pubcount);
		request.setAttribute("currentpage",new Integer(currentPage));  	
		request.setAttribute("pageStytle", "bbstext");
    	String searchStr=MyUtil.getParams(request);
		request.setAttribute("searchStr",searchStr);
		List<CorpPublication> corpPublicationList = corpPublicationMng.findByPage(currentPage, pageSize, param); 
		request.setAttribute("corpPublicationList", corpPublicationList); 
		
		
		String dictCode = "1002";
		String parentId = "0";
		
		request.setAttribute("typeDicts", appDictMng
				.getfindByDictCode(dictCode));
		request.setAttribute("corpCatalogs", corpCatalogMng
				.getCorpCatalogByParentId(parentId));
		request.setAttribute("imagepath", Config.ImageServerURL_CORPPUBIMG);
		request.setAttribute("thumbpath", Config.FileNameTopThumb);
		String controlCode="空间大小";
//		查找限制数目;
		List dictList=(List) session.getAttribute("dict");
		long leftSize=0;
		if(dictList!=null&&dictList.size()>0){
			for(Iterator ir=dictList.iterator();ir.hasNext();){
				AppDict dict=(AppDict) ir.next();
				if(dict!=null){
					if(dict.getClassCode().indexOf(controlCode)>-1){
						int count=	corpPublicationMng.getCount(param);
						long restrainSize=StringUtil.stringToLong(dict.getClassValue())*1024*1024;
					    leftSize=((restrainSize-count)/1024)/1024;
					    if(leftSize<0) leftSize=0;
						break;
					}
				}
			}
			
		}
		request.setAttribute("leftsize", leftSize);
//		电子书剩余空间
		request.setAttribute("leftsize", leftSize);
		String fileFormat="*.jpg;*.JPG;*.jpeg;*,JPEG;*swf";
		request.setAttribute("fileformat",fileFormat);
		return "listno";
	}
	
	public String recycle() {
		int pageSize=10;
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		CorpCommpany corpCommpany = (CorpCommpany) session.getAttribute("corpCommpany");
		String corpId = corpCommpany.getId()+"";
		
		HashMap<String,Object> param =new HashMap<String,Object>();
//    	按关键字查询
		String key=request.getParameter("key");			
		if(key!=null&& key.length()>0){
			param.put("title", key);
			request.setAttribute("key",key);
		}
			
		if(corpId!=null&& corpId.length()>0){
			param.put("corpId", corpId);
		}	
		param.put("isValid",new Integer(2));
		
		int currentPage=1; 
		String currentpageTemp=request.getParameter("currentpage");
		if(currentpageTemp!=null){
			try {
				currentPage=new Integer(currentpageTemp).intValue();	
			} catch (Exception e) {
				currentPage=1;
			}
			
		}
    	int pubcount = corpPublicationMng.getCount(param);
    	request.setAttribute("pubcount", pubcount);
		request.setAttribute("currentpage",new Integer(currentPage));  	
		request.setAttribute("pageStytle", "bbstext");
    	String searchStr=MyUtil.getParams(request);
		request.setAttribute("searchStr",searchStr);
		List<CorpPublication> corpPublicationList = corpPublicationMng.findByPage(currentPage, pageSize, param); 
		request.setAttribute("corpPublicationList", corpPublicationList); 
		
		
		String dictCode = "1002";
		String parentId = "0";
		
		request.setAttribute("typeDicts", appDictMng
				.getfindByDictCode(dictCode));
		request.setAttribute("corpCatalogs", corpCatalogMng
				.getCorpCatalogByParentId(parentId));
		request.setAttribute("imagepath", Config.ImageServerURL_CORPPUBIMG);
		request.setAttribute("thumbpath", Config.FileNameTopThumb);
		String controlCode="空间大小";
//		查找限制数目;
		List dictList=(List) session.getAttribute("dict");
		long leftSize=0;
		if(dictList!=null&&dictList.size()>0){
			for(Iterator ir=dictList.iterator();ir.hasNext();){
				AppDict dict=(AppDict) ir.next();
				if(dict!=null){
					if(dict.getClassCode().indexOf(controlCode)>-1){
						int count=	corpPublicationMng.getCount(param);
						long restrainSize=StringUtil.stringToLong(dict.getClassValue())*1024*1024;
					    leftSize=((restrainSize-count)/1024)/1024;
					    if(leftSize<0) leftSize=0;
						break;
					}
				}
			}
			
		}
		request.setAttribute("leftsize", leftSize);
//		电子书剩余空间
		request.setAttribute("leftsize", leftSize);
		String fileFormat="*.jpg;*.JPG;*.jpeg;*,JPEG;*swf";
		request.setAttribute("fileformat",fileFormat);
		return "recycle";
	}
	
	public String add() throws Exception {
		String display = "list";
		String resultFilename;
		int width = 0, height = 0;
		int fileSize=0;
		int backFileSize=0;
		HttpServletRequest request = ServletActionContext.getRequest();
		String root = ServletActionContext.getServletContext().getRealPath(
		"/expo/pub");
		corpPublication.setId(appSeqMng.getSequence("corp_publication_seq").intValue());
		Date date = new Date();
		corpPublication.setCreateDate(date);
		HttpSession session = request.getSession(true);
		CorpCommpany corpCommpany = (CorpCommpany) session.getAttribute("corpCommpany");
		// 本地临时路径
		String username = corpCommpany.getId()+"";
		String corpId = corpCommpany.getId()+"";
		String controlCode=request.getParameter("controlCode");
//		查找限制数目;
		List dictList=(List) session.getAttribute("dict");
		HashMap<String,Object> param =new HashMap<String,Object>();
		if(dictList!=null&&dictList.size()>0){
			for(Iterator ir=dictList.iterator();ir.hasNext();){
				AppDict dict=(AppDict) ir.next();
				if(dict!=null){
					if(dict.getClassCode().indexOf(controlCode)>-1){
						long count=	corpPublicationMng.getCount(param);
						if(count>=StringUtil.stringToLong(dict.getClassValue())*1024*1024){
//							 返回提示信息
							HtmlMessageBox hmb = new HtmlMessageBox();
							hmb.setEnabledTimer(true);
							hmb.setTimer(5);// 倒计时秒数,默认5秒

							String httppath="http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
							hmb.setMessageOnPageType(HtmlMessageBox.MESSAGE_ON_PAGE_SPECIFY_URL);// .MESSAGE_ON_PAGE_PR
							// EACTION_URL);
							hmb.setMessageOnPageURL(httppath + "/corp/corpPublication_show.do");
					
							// 保存数据
							hmb.setMessage("新增失败！电子书空间已到"+(count/1024)/1024+"M,若需继续新增,请升级会员！");// 提示信息		
							hmb.setForwardUrl(new String[] {
									httppath + "/corp/corpPublication_list.do",
									httppath + "/corp/corpPublication_show.do" });// 提示信息页面设置链接到指定位置
							hmb.setLinkMsg(new String[] { "到列表", "继续新增" });// 链接到指定位置的提示信息
							display = this.displayMessage(request,hmb, "big");

							return display;
						}
						break;
					}
				}
				
				
			}
			
		}
//		 电子书期刊
		String pubmagazinecount =corpPublicationMng.getPulicationName(corpId);

		// 电子书路径

		String pubpath =  corpId+ "/" + pubmagazinecount;

		InputStream fileIn=null;
		JPEGImageDecoder decoder = null;
		BufferedImage bufImage = null;
		try {
			fileIn = new FileInputStream(thumb);
			fileSize = fileIn.available();// 取得文件尺寸
			if (!fileIn.equals(null) && !fileIn.equals("")) {
				decoder = JPEGCodec.createJPEGDecoder(fileIn);
				bufImage = decoder.decodeAsBufferedImage();
				width = bufImage.getWidth();
				height = bufImage.getHeight();

			}
		} catch (Exception e) {
			// TODO: handle exception
			if (bufImage != null) {
				bufImage.flush();
			}
			e.printStackTrace();
		} finally {
			if (decoder != null) {
				decoder = null;
			}
			if (bufImage != null) {
				bufImage.flush();
			}
			try {
				if (fileIn != null) {
					fileIn.close();
				}
			} catch (Exception e) {
				fileIn = null;
			}
		}
		// 根据电子书类型判断宽度 1单页 2双页
		// if(publication.getPubtype()==1){
		if (width <= 1100 && width >= 200) {
			// 将宽度与高度设置到pulication
			corpPublication.setWidth(width);
			corpPublication.setHeight(height);
		} else {
				HtmlMessageBox hmb = new HtmlMessageBox();
				hmb.setEnabledTimer(true);
				hmb.setTimer(5);// 倒计时秒数,默认5秒

				String httppath="http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
				hmb.setMessageOnPageType(HtmlMessageBox.MESSAGE_ON_PAGE_SPECIFY_URL);// .MESSAGE_ON_PAGE_PR
				// EACTION_URL);
				hmb.setMessageOnPageURL(httppath + "/corp/corpPublication_show.do");
		
				// 保存数据
				hmb.setMessage("新增失败！电子格式中的宽度不在,200px~1100px之间！");// 提示信息		
				hmb.setForwardUrl(new String[] {
						httppath + "/corp/corpPublication_list.do",
						httppath + "/corp/corpPublication_show.do" });// 提示信息页面设置链接到指定位置
				hmb.setLinkMsg(new String[] { "到列表", "继续新增" });// 链接到指定位置的提示信息
				display = this.displayMessage(request,hmb, "big");
			return display;
		}
		UploadImage uploadimage = new UploadImage();
		resultFilename = uploadimage.UploadImages(thumb,thumbFileName,username, root,
				Config.UpIMGTypePub, pubpath, Config.StrTop, Config.StrNoBottom,
				Config.StrNoBackGroup, width, height,corpPublication.getPubType());
		corpPublication.setThumbPath(resultFilename);
		if(corpPublication.getPagesCount()==null){
			corpPublication.setPagesCount(1);
		}else{
			corpPublication.setPagesCount(corpPublication.getPagesCount() + 1);
		}		
		corpPublication.setPubmemSize(fileSize);

		try {
			fileIn = new FileInputStream(endpicture);
			backFileSize = fileIn.available();// 取得文件尺寸			
		} catch (Exception e) {			
			e.printStackTrace();
		} finally {
			try {
				if (fileIn != null) {
					fileIn.close();
				}
			} catch (Exception e) {
				fileIn = null;
			}
		}
		
		resultFilename = uploadimage.UploadImages(endpicture, endpictureFileName,username, root,
				Config.UpIMGTypePub, pubpath, Config.StrNoTop,Config.StrBottom,
				Config.StrNoBackGroup, width, height, ExtendString
						.parseInt(corpPublication.getPubType() + ""));
		corpPublication.setEndPath(resultFilename);
		corpPublication.setPagesCount(corpPublication.getPagesCount() + 1);
		corpPublication.setPubmemSize(corpPublication.getPubmemSize()
				+ backFileSize);
		corpPublication.setPubBackgroudSize(backFileSize);
		
//		 默认信息
		corpPublication.setPubmemSize(corpPublication.getPubmemSize()
				+ corpPublication.getPubBackgroudSize());
		corpPublication.setPubType(new Integer(ExtendString.nullToSpaceNoTrim(request.getParameter("pubType"))));
		corpPublication.setCorpId(corpId);
		corpPublication.setCreateDate(date);
		corpPublication.setModDate(date);
		corpPublication.setPubPath(pubpath);
		corpPublication.setSounLoop(0);
		corpPublication.setHits(0);
		corpPublication.setIsAuditing(0);
		corpPublication.setComments(0);
		corpPublication.setIsCommend(0);
		corpPublication.setIsValid(0);
		corpPublication.setPubZoom(0);
		corpPublication.setBackgroundRepeat(0);
		corpPublication.setTypeId(new Integer(ExtendString.nullToSpaceNoTrim(request.getParameter("typeId"))));
		corpPublication.setPubMagazineCount(StringUtil.stringToInt(pubmagazinecount));
		corpPublication.setBackgroundAlpha(Config.Backgroundalpha);
		corpPublication.setIsCommpany(0);
		// 以下为高级设置为空时调用默认设置
		HtmlMessageBox hmb = new HtmlMessageBox();
		hmb.setEnabledTimer(true);// 是否在页面有计时
		hmb.setTimer(5);// 倒计时秒数,默认5秒


		hmb.setMessageOnPageType(HtmlMessageBox.MESSAGE_ON_PAGE_SPECIFY_URL);// .MESSAGE_ON_PAGE_PREACTION_URL);
		String httppath="http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		hmb.setMessageOnPageURL(httppath+"/corp/corpPublication_list.do");
		corpPublicationMng.add(corpPublication);
		// 生产XML
		new UploadXml().UploadXml(corpPublication, null, root);
		hmb.setMessage("新增成功！");// 提示信息
		hmb.setForwardUrl(new String[] {
					httppath+"/corp/corpPublication_list.do",
									httppath+"/corp/corpPublication_newshow.do"});// 提示信息页面设置链接到指定位置
			hmb.setLinkMsg(new String[] { "到列表", "继续新增" });// 链接到指定位置的提示信息

			display = this.displayMessage(request,hmb, "big");
		//corpPublication=uploadPub(corpPublication, thumb,thumbFileName,root);
		
	
		return display;
	}
	
	

//	private CorpPublication uploadPub(CorpPublication corpPublication, File file,String fileName,String root)
//			throws Exception {
//
//		String path = root + "\\" + fileName;
//		InputStream in = null;
//		OutputStream out = null;
//		BufferedInputStream bis = null;
//		BufferedOutputStream bos = null;
//		int width = 0, height = 0;
//		JPEGImageDecoder decoder = null;
//		BufferedImage bufImage = null;
//
//		try {
//			in = new FileInputStream(file);
//			out = new FileOutputStream(new File(path));
//			bis = new BufferedInputStream(in);
//			bos = new BufferedOutputStream(out);
//			byte[] buf = new byte[(int) file.length()];
//			int len = 0;
//			while (((len = bis.read(buf)) != -1)) {
//				bos.write(buf, 0, len);
//			}
//			
//			try {
//				decoder = JPEGCodec.createJPEGDecoder(in);
//				bufImage = decoder.decodeAsBufferedImage();
//				width = bufImage.getWidth();
//				height = bufImage.getHeight();
//			} catch (Exception e) {
//				if (bufImage != null) {
//					bufImage.flush();
//				}
//				e.printStackTrace();
//			} finally {
//				if (decoder != null) {
//					decoder = null;
//				}
//				if (bufImage != null) {
//					bufImage.flush();
//				}
//			}
//			if (width <= 1100 && width >= 200) {
//				// 将宽度与高度设置到pulication
//				corpPublication.setWidth(width);
//				corpPublication.setHeight(height);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (bos != null) {
//					bos.close();
//				}
//				if (bis != null) {
//					bis.close();
//				}
//			} catch (Exception e) {
//				bos = null;
//				bis = null;
//			}
//
//			try {
//				if (in != null) {
//					in.close();
//				}
//				if (out != null) {
//					out.close();
//				}
//			} catch (Exception e) {
//				in = null;
//				out = null;
//			}
//		}
//		return corpPublication;
//	}

	

	public File getEndpicture() {
		return endpicture;
	}

	public void setEndpicture(File endpicture) {
		this.endpicture = endpicture;
	}

	public String getEndpictureFileName() {
		return endpictureFileName;
	}

	public void setEndpictureFileName(String endpictureFileName) {
		this.endpictureFileName = endpictureFileName;
	}

	public File getThumb() {
		return thumb;
	}

	public void setThumb(File thumb) {
		this.thumb = thumb;
	}

	public String getThumbFileName() {
		return thumbFileName;
	}

	public void setThumbFileName(String thumbFileName) {
		this.thumbFileName = thumbFileName;
	}

}
